<template>
	<view class="goodsdetail">
		<page-head :transparent='true'>
			<slot slot="title">{{title.length>10?title.substr(0,10)+'...':title}}</slot>
			<slot slot="right">{{''}}</slot>
		</page-head>
		<view class="goods-detail-row">
			<view class="goods-detail-img">
				<lazy-image class="lazy-image" :realSrc="picUrl"></lazy-image>
				<!-- <image :src="picUrl" mode="aspectFill"></image> -->
			</view>
			<view class="goods-detail-title">{{ skuName }}</view>
			<view class="goods-detail-money">
				<text class="money-text">
					到手价
					<text class="money-price">￥{{ wlPrice_after }}</text>
				</text>
			</view>
			<view style="height: 10px;"></view>

			<!-- <view class="goods-detail-coupon">
				<text>抵￥{{ discount }}</text>
			</view> -->

			<view class="goods-detail-coupon" @click="validaUserInfo" v-if="discount != ''">
				<view class="coupen-price">
					<view class="coupen-money">抵 ￥{{ discount }}</view>
				</view>
				<view class="coupen-time-rang">点击领取</view>
			</view>

			<view style="height: 10px;"></view>
			<!-- <view class="goods-detail-btn"><button @click="validaUserInfo">立即兑换</button></view> -->
		</view>

		<!-- 查看详情 -->
		<view class="look-detil" @click="lookDetil">
			查看详情
			<image :class="[detilMsg ? 'rotate' : '']" src="../../static/img/search/down.png" mode="aspectFill"></image>
		</view>

		<view class="products-detail" :class="[detilMsg ? 'products-detail1' : 'products-detail2']">
			<view class="products-detail-img" v-for="(item, index) in detailList" :key="index">
				<image :src="item" mode="aspectFill"></image>
			</view>
		</view>

		<view class="hot-row"><text>热门推荐</text></view>
		<w-goods-list :goodsList="goodsList" @eventClick="toDetail" @eventPlatform="startWebview" :loadingText="'我也是有底线的'"></w-goods-list>
		<foot-tab :footerList="footerList" @goSeller="toZy(footerList[0].item_url)" @goChange="validaUserInfo"></foot-tab>
		<w-loading text="加载中.." mask="1" click="0" ref="loading"></w-loading>
	</view>
</template>

<script>
	let seller = '',
		skuId = '',
		absoluteUrl = '';
	export default {
		onShow() {
			this.genToken();
		},
		onLoad(event) {
			seller = event.seller;
			skuId = event.skuId;
			let cid = event.cid;
			/* if (event.token != '' && event.token != 'null' && event.token != null && event.token != undefined && event.token != 'undefined') {
				uni.setStorageSync('token', decodeURI(event.token));
				uni.setStorageSync('bump', event.bump);
				uni.setStorageSync('relationId', event.relationId);
				uni.setStorageSync('mobile', event.customerId);
			} */
		},
		data() {
			return {
				goodsList: [],
				picUrl: '',
				skuName: '',
				wlPrice_after: '',
				discount: '',
				spread_start_at: '',
				spread_end_at: '',
				detailList: [],
				detilMsg: false,
				footerList: [],
				title: '',
			};
		},
		methods: {
			genToken() {
				const that = this
				let url = window.location.href;
				console.log("url===" + url);
				let reg_url = /^[^\?]+\?([\w\W]+)$/,
					reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
					arr_url = reg_url.exec(url),
					ret = {};
				if (arr_url && arr_url[1]) {
					let str_para = arr_url[1],
						result;
					while ((result = reg_para.exec(str_para)) != null) {
						ret[result[1]] = result[2];
					}
				}
				let token = ret.token;
				if (token != '' && token != 'null' && token != null && token != undefined && token != 'undefined') {
					// uni.setStorageSync('token', decodeURI(token));
					uni.setStorageSync('token', decodeURI(token));
					uni.setStorageSync('bump', ret.bump);
					uni.setStorageSync('relationId', ret.relationId);
					uni.setStorageSync('mobile', ret.customerId);
				}
				this.genGoodsDetail(skuId);
				this.genHotGoodsList(cid);
			},
			startWebview(url) {
				appNavigateTo(url);
			},
			toZy(url) {
				let bump = uni.getStorageSync('bump');
				if (bump != '' && bump != 'null' && bump != null && bump != undefined && bump != 'undefined') {
					appNavigateTo(url);
				} else {
					this.valida();
				}
			},
			validaUserInfo() {
				try {
					onEvent('page_home_icon_haopingou_goods_dissipate');
					let userInfo = uni.getStorageSync('token');
					if (userInfo != '' && userInfo != null) {
						this.jardgeUserChange();
					} else {
						this.valida();
					}
				} catch (e) {
					console.log("catch userInfo===" + e.message)
					this.valida();
				}
			},
			jardgeUserChange() {
				uni.request({
					url: this.$usereq + '/coupon-customer/rechargeable/consume/validatorDeduction',
					method: 'POST',
					header: {
						'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
						'content-type': 'application/json'
					},
					data: {
						deduction: '0', //平台id
						deductionAmount: this.discount,
						picUrl: this.picUrl,
						skuId: skuId,
						skuName: this.skuName,
						wlPrice: this.footerList[0].wlPrice,
						wlPriceAfter: this.wlPrice_after,
						endTime: '',
						startTime: '',
						htmlQuanUrl: ''
					},
					success: res => {
						let datas = res.data;
						if (datas.code == 200) {
							uni.showModal({
								title: '',
								content: '您已兑换过该优惠券，现在去购买吗？',
								showCancel: true,
								cancelText: '取消',
								confirmText: '确定',
								success: res => {
									if (res.confirm) {
										let result = datas.data;
										appNavigateTo(result.htmlQuanUrl)
									}
								}
							});
						} else {
							this.selfChange();
						}
					}
				});
			},
			valida() {
				console.log('no token====' + uni.getSystemInfoSync().platform);
				onStartLogin()
			},
			selfChange() {
				uni.showModal({
					content: '确认使用余额兑换该优惠券，此操作不可撤销？',
					showCancel: true,
					success: res => {
						if (res.confirm) {
							this.$refs.loading.open();
							onEvent('page_home_icon_haopingou_goods_dissipate_sure');
							this.exchangeUrl();
						}
					}
				});
			},
			genStartTime() {
				let myDate = new Date();
				let fullYear = myDate.getFullYear();
				let month = myDate.getMonth() + 1;
				let day = myDate.getDate();
				return fullYear + '/' + month + '/' + day;
			},
			genEndTime() {
				let myDate = new Date();
				let fullYear = myDate.getFullYear() + 1;
				let month = myDate.getMonth() + 1;
				let day = myDate.getDate();
				return fullYear + '/' + month + '/' + day;
			},
			async exchangeUrl() {
				try {
					let startTime = this.genStartTime();
					let endTime = this.genEndTime();
					uni.request({
						url: this.$usereq + '/coupon-customer/rechargeable/consume/deduction',
						method: 'POST',
						dataType: 'json',
						withCredentials: true,
						header: {
							'content-type': 'application/json',
							'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token)
						},
						data: {
							deduction: '0', //平台id
							deductionAmount: this.discount,
							picUrl: this.picUrl,
							skuId: skuId,
							skuName: this.skuName,
							wlPrice: this.footerList[0].wlPrice,
							wlPriceAfter: this.wlPrice_after,
							endTime: endTime.replace('/', '-').replace('/', '-'),
							startTime: startTime.replace('/', '-').replace('/', '-'),
							htmlQuanUrl: encodeURIComponent(absoluteUrl)
						},
						success: res => {
							this.$refs.loading.close();
							let datas = res.data;
							if (datas.code == 200) {
								uni.showToast({
									icon: 'none',
									title: '领取成功'
								});
								let bump = uni.getStorageSync('bump');
								appNavigateTo(absoluteUrl + '&discount=' + datas.data);
							} else if (datas.code == 401) {
								this.valida();
							} else {
								uni.showToast({
									icon: 'none',
									title: datas.msg
								});
							}
						}
					});
				} catch (e) {
					uni.hideLoading();
					console.log(e.message);
				}
			},
			async genGoodsDetail(skuId) {
				try {
					uni.showLoading({
						title: 'loading...',
						mask: true
					});
					uni.request({
						url: this.$usereq + '/coupon-product/self/product/optimization/' + skuId,
						method: 'GET',
						header: {
							'content-type': 'application/json',
							'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token)
						},
						data: {},
						success: res => {
							let datas = res.data.data;
							console.log('goodsName===' + datas.proName);
							this.ti = datas.proName;
							this.setTitle(datas.proName)
							this.detailList = datas.pics;
							this.picUrl = datas.pic;
							this.skuName = datas.proName;
							this.wlPrice_after = datas.discountPrice;
							this.discount = parseInt(datas.customerCommision);
							let bump = uni.getStorageSync('bump');
							absoluteUrl = datas.absoluteUrl + '&fromapp=1&bump=' + bump + '&disable_order_direct_discount=1';
							let sellerGo = datas.supplerType == 1 ? '去京东比价' : '好品购';
							let contrastUrl = datas.contrastUrl;
							let item_url = datas.supplerType == '1' || datas.supplerType == 1 ? contrastUrl : absoluteUrl;
							this.footerList = [{
								wlPrice: datas.minPrice,
								sellerGo: sellerGo,
								wlPrice_after: datas.discountPrice,
								item_url: item_url
							}];
							uni.hideLoading();
						}
					});
				} catch (e) {
					uni.hideLoading();
					console.log(e);
				}
			},
			lookDetil() {
				if (this.detilMsg) {
					this.detilMsg = false;
				} else {
					this.detilMsg = true;
				}
			},
			setBackColor() {
				// #ifdef H5
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef APP-PLUS
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef MP
				uni.setNavigationBarColor({
					frontColor: '#000000',
					background: '#FF0000'
				});
				// #endif
			},
			async genHotGoodsList(cid) {
				try {
					let data = {
						page: 1,
						pageSize: 20,
						cateId: ''
					};
					let res = await this.$request.get('/coupon-product/self/product/optimization', {
						data: data
					});
					let datas = res.data;
					let newList = datas.data;
					if (newList != '' && newList.length > 0) {
						this.goodsList = this.goodsList.concat(newList);
					}
				} catch (e) {
					console.log(e);
					this.loadingText = '没有更多了';
				}
			},
			setTitle(title) {
				this.title = title;
				uni.setNavigationBarTitle({
					title: title
				});
			},
			toDetail(e) {
				onEvent('page_home_icon_haopingou_goods');
				setTimeout(function() {
					h5RedirectTo({
						url: '../selfdetail/selfdetail?skuId=' + e.id + '&cid=' + e.cateids + '&title=' + e.proName + '&seller=京东自营'
					});
				}, 1000);
			}
		}
	};
</script>

<style lang="scss">
	@import '@/common/css/goods-list.scss';

	.coupen-price {
		margin-top: 24px !important;
	}
</style>
